package com.fanyi.impl;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.NameValuePair;

import com.alibaba.fastjson.JSON;
import com.fanyi.TranslateExecution;
import com.fanyi.baidu.BaiduTransResult;
import com.util.HttpClientUtil;

/**
 * @author liuchao
 * @version $Id: BaiduTranslate.java,v 0.1 2012-10-9 下午11:05:15 liuchao Exp $
 */
public class BaiduTranslate implements TranslateExecution {
    
    private  final static String url = "http://openapi.baidu.com/public/2.0/bmt/translate";

    @Override
    public String translate(String from) throws Exception{
        
        Map<String, String> parame = new HashMap<String,String>();
        parame.put("client_id", "3QWsqZ0C5XEKVBgRQ56Kigjb");
        parame.put("q", URLEncoder.encode("测试","UTF-8"));
        parame.put("from", "en");
        parame.put("to", "en");
        int i = 0;
        NameValuePair[] nameValue = new NameValuePair[parame.size()];
        StringBuffer data = new StringBuffer().append(url).append("?");
                for (String key : parame.keySet()) {
                    nameValue[i++] = new NameValuePair(key, parame.get(key));
                    data.append(key + "=" + parame.get(key) + "&");
                }
        Map<String, String> backMap = HttpClientUtil.getHttpClientXML(data.toString());
        String backXML = backMap.get("backXml");
        BaiduTransResult baiduTransResult = JSON.parseObject(backXML.trim(),BaiduTransResult.class);
        if( null == baiduTransResult.getError_code() ){
            return baiduTransResult.getTrans_result().get(0).getDst();
        }
        return null;
    }

}
